package jeesample.dao;

import java.sql.SQLException;
import java.util.ResourceBundle;

import jeesample.model.Booking;
import jeesample.model.Room;

import org.apache.log4j.Logger;

import com.j256.ormlite.jdbc.JdbcPooledConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class OrmLiteManager {
	private static Logger logger = Logger.getLogger(OrmLiteManager.class);
	private static ConnectionSource connectionSource = null; 
	
	static {
		if (connectionSource == null) {
			initialize();
		}
	}

	public static void initialize() {
		if (connectionSource != null) {
			return; // already done once.
		}
		// code below only executes if not done once.
		initConnection();
		initTables();		
		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				destroyed();
			}
		});
	}

	public static void initTables() {
		Class[] classes = { Booking.class, Room.class };
		for (Class model : classes) {
			try {
				TableUtils.createTable(connectionSource, model);
				// TableUtils.createTableIfNotExists(connectionSource, model);
			} catch (SQLException e) {
				logger.error("Failure to create Table:" + model.getName(), e);
			}
		}
	}

	public static ConnectionSource getConnectionSource() {
		if (connectionSource == null) {
			initialize();
		}		
		return connectionSource;
	}

	public static void destroyed() {
		if (connectionSource == null) {
			return;
		}
		if(connectionSource.isOpen()){
			connectionSource.closeQuietly();
		}
		connectionSource=null;
	}

	public static void initConnection() {
		// pooled connection source
		JdbcPooledConnectionSource pooledSource;
		ResourceBundle bundle = ResourceBundle.getBundle("OrmLiteManager");
		try {
			String jdbcUrl = bundle.getString("jdbc.url");
			if (jdbcUrl.isEmpty()) {
				jdbcUrl = "jdbc:h2:mem:jeesample";
			}
			String login = bundle.getString("jdbc.login");
			if (login.isEmpty()) {
				login = "SA";
			}
			String password = bundle.getString("jdbc.password");
			if (password.isEmpty()) {
				password = "";
			}
			pooledSource = new JdbcPooledConnectionSource(jdbcUrl, login,
					password);
			// only keep the connections open for 5 minutes
			pooledSource.setMaxConnectionAgeMillis(5 * 60 * 1000);
			// change the check-every milliseconds from 30 seconds to 60
			pooledSource.setCheckConnectionsEveryMillis(60 * 1000);
			pooledSource.setTestBeforeGet(true);
			connectionSource = pooledSource;
		} catch (SQLException e) {
			logger.error("Failure to obtain a connection source:", e);
		}
	}

}
